from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone

class UserManager(BaseUserManager):
    def create_user(self, username, password=None, name='', role=0):
        if not username:
            raise ValueError('Users must have a username')

        user = self.model(
            username=username,
            name=name,
            role=role,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, name='', role=1):
        user = self.create_user(
            username=username,
            password=password,
            name=name,
            role=role,
        )
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    user_id = models.AutoField(primary_key=True)
    username = models.CharField(unique=True, max_length=16)
    password = models.CharField(max_length=128)
    name = models.CharField(max_length=50)
    ROLE_CHOICES = (
        (0, 'User'),
        (1, 'Admin'),
    )
    role = models.IntegerField(choices=ROLE_CHOICES, default=0)
    create_time = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(null=True, blank=True)

    USERNAME_FIELD = 'username'

    objects = UserManager()

    def __str__(self):
        return self.username

    def check_password(self, raw_password):
        # Implement password checking logic here
        return self.password == raw_password  # Replace with actual password checking

    def set_password(self, raw_password):
        # Implement password hashing logic here
        self.password = raw_password

    def save(self, *args, **kwargs):
        # Override save method to set last_login
        if self.last_login is None:
            self.last_login = timezone.now()
        super().save(*args, **kwargs)
